﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace Gama.Extension
{
    public static partial class HtmlHelperExtensions
    {
        public static void RenderPartialEx<TModel>(this HtmlHelper htmlHelper, string partialViewName, TModel model, Expression<Func<TModel, object>> expression)
            where TModel : class
        {
            using (htmlHelper.BeginBindingSection(expression))
            {
                htmlHelper.RenderPartial(partialViewName, expression.Compile()(model));
            }
        }

        public static void RenderPartialEx<TModel>(this HtmlHelper htmlHelper, string partialViewName, TModel model, Expression<Func<TModel, object>> expression, object htmlAttributes)
            where TModel : class
        {
            using (htmlHelper.BeginBindingSection(expression))
            {
                htmlHelper.RenderPartial(partialViewName, expression.Compile()(model), BuildViewDataDictionaryFromProperties(htmlAttributes));
            }
        }

        internal static ViewDataDictionary BuildViewDataDictionaryFromProperties(object @object)
        {
            var dictionary = new ViewDataDictionary();

            if (@object != null)
            {
                foreach (var propertyDescriptor in TypeDescriptor.GetProperties(@object).Cast<PropertyDescriptor>())
                {
                    dictionary.Add(propertyDescriptor.Name, propertyDescriptor.GetValue(@object));
                }
            }

            return dictionary;
        }
    }
}
